import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getWeatherAll, getWeatherBase, getInputCity, getLocalCity } from '../api/index'


export const useWeatherStore = defineStore('weather', () => {
  const cityList = ref([])
  const allWeatherData = ref([])
  const dayTemp = ref([])
  const nightTemp = ref([])
  const LocalCityData = ref({})
  const option = ref({})
  const inputCity = ref('')
  const adcode = ref('')
  const cityBaseData = ref({})
  const noCity = ref(false)
  const buttonShow = ref(false)
  const p = ref([])

  //获取当前城市天气数据
  const getLocalData = () => {
    dayTemp.value = []
    nightTemp.value = []
    getLocalCity().then((res) => {
      const city = res.city
      getWeatherBase(city).then((res) => {
        if (res.status == 1) {
          LocalCityData.value = res.lives[0]
        }
      })
      getWeatherAll(city).then((res) => {
        if (res.status == 1) {
          allWeatherData.value = res.forecasts[0].casts
          getAllData()
          renderChart(dayTemp.value, nightTemp.value)
        }
      })
    })
  }

  const getAllData = () => {
    allWeatherData.value.map((item, index) => {
      if (index == 0) {
        item.weekDay = '今天'
      } else if (index == 1) {
        item.weekDay = '明天'
      } else {
        const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        item.weekDay = weekDays[item.week - 1]
      }
      dayTemp.value.push(item.daytemp)
      nightTemp.value.push(item.nighttemp)
    })
  }

  //搜索城市
  const getInputData = (city) => {
    getInputCity(city)
      .then((res) => {
        if (res.status == 1) {
          adcode.value = res.geocodes[0].adcode
          inputCity.value = res.geocodes[0].city
          noCity.value = false
          return
        } else if (res.status == 0) {
          noCity.value = true
          inputCity.value = ''
        }
      })
      .catch(() => {
        inputCity.value = ''
      })
  }

  //获取输入城市天气数据
  const getInputCityData = (adcode) => {
    dayTemp.value = []
    nightTemp.value = []
    getWeatherBase(adcode).then((res) => {
      if (res.status == 1) {
        cityBaseData.value = res.lives[0]
      }
    })
    getWeatherAll(adcode).then((res) => {
      if (res.status == 1) {
        allWeatherData.value = res.forecasts[0].casts
        getAllData()
        renderChart(dayTemp.value, nightTemp.value)
      }
    })
    if (cityList.value.some((item) => item.id === adcode)) {
      buttonShow.value = false
    } else {
      buttonShow.value = true
    }
  }

  const renderChart = (data1, data2) => {
    option.value = {
      xAxis: {
        type: 'category',
        show: false
      },
      yAxis: {
        type: 'value',
        show: false
      },
      grid: {
        top: 30,
        left: 0,
        right: 0,
        bottom: 0
      },
      series: [
        {
          type: 'line',
          data: data1,
          smooth: true,
          label: {
            show: true,
            position: 'top',
            formatter: function (params) {
              return '白' + params.value + '°C'
            },
            color: '#fff',
            fontSize: 12
          }
        },
        {
          type: 'line',
          data: data2,
          smooth: true,
          label: {
            show: true,
            position: 'bottom',
            formatter: function (params) {
              return '晚' + params.value + '°C'
            },
            color: '#fff',
            fontSize: 12
          }
        }
      ]
    }
  }

  //添加城市
  const handleAddCity = () => {
    cityList.value.push({
      id: adcode.value,
      name: inputCity.value,
      temperature: cityBaseData.value.temperature
    })
  }

  //删除城市
  const deleteCity = (id) => {
    const index = cityList.value.findIndex((item) => item.id === id)
    cityList.value.splice(index, 1)
  }

  //读取城市列表
  // const readCityList = () => {
  //   const cityListStr = localStorage.getItem('cityList')
  //   if (cityListStr) {
  //     cityList.value = JSON.parse(cityListStr)
  //   } else {
  //     cityList.value = []
  //   }
  // }

  //更新城市列表
  const updataCityList = () => {
    const upcityList = JSON.parse(localStorage.getItem('cityList'))
    for (let i = 0; i < upcityList.length; i++) {
      const pi = getWeatherBase(upcityList[i].id).then((res) => res)
      p.value.push(pi)
    }
    Promise.all(p.value).then((res) => {
      // console.log(res)
      // cityList.value=[]
      for (let i = 0; i < res.length; i++) {
        // cityList.value[i].temperature = res[i].lives[0].temperature

        cityList.value.push({
          id: res[i].lives[0].adcode,
          name: res[i].lives[0].city,
          temperature: res[i].lives[0].temperature
        })
      }
      // readCityList()
      // console.log(cityList)
    })
  }

  updataCityList()

  watch(cityList.value, () => {
    console.log(123)
    localStorage.setItem('cityList', JSON.stringify(cityList.value))
  })

  getLocalData()

  return {
    cityList,
    inputCity,
    adcode,
    cityBaseData,
    noCity,
    buttonShow,
    option,
    dayTemp,
    nightTemp,
    LocalCityData,
    allWeatherData,
    getAllData,
    getLocalData,
    handleAddCity,
    getInputCityData,
    getInputData,
    deleteCity,
    updataCityList
  }
})
